﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace LinkClient_
{
    public partial class FormMain : Form
    {
        InitFile init = new InitFile();
        MsSqlHelper mssql = new MsSqlHelper();
        public delegate void EventHandle();
        public static event EventHandle MyEvent;

        public DataTable dtdrug = new DataTable();

        private int totalCount = 0;
        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            if (init.AutoSync)
            {
                timer.Enabled = true;
                init.WriteLog("自动更获取数据已启动",false);
                this.WindowState = FormWindowState.Minimized;
            }            
            try
            {
                Observer observer = new Observer();
                this.Text = this.Text +" 【"+ observer.GetEntName()+"】";
                dtdrug = mssql.ExecuteDt(init.DrugSql);
                dtdrug.Columns.Add("pym", Type.GetType("System.String"));
            }
            catch (Exception ex)
            {
                init.WriteLog(ex.ToString(), true);
                MessageBox.Show("出错了！\r\n错误信息："+ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();            //关闭应用程序窗体                
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Observer observer = new Observer();
            try
            {
                observer.GetSaleData();                
                MessageBox.Show("更新完成");
            }
            catch (Exception ex)
            {
                init.WriteLog(ex.ToString(), true);
            }
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            init.WriteLog("测试~",false);
            Thread objThread = new Thread(new ThreadStart(delegate
            {
                ThreadMethod();
            }));
            objThread.Start();
        }

        public void ThreadMethod()
        {
            if (init.getTimeSpan("08:00", "18:00"))
            {
                Observer observer = new Observer();
                //MyEvent += new EventHandle(observer.GetData);
                MyEvent += new EventHandle(observer.GetSaleData);
                Delegate[] delegates = MyEvent.GetInvocationList();
                foreach (EventHandle del in delegates)
                {
                    try
                    {
                        del();
                    }
                    catch (Exception ex)
                    {
                        //异常处理；
                        init.WriteLog(ex.ToString(), true);
                    }
                }
            }
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //判断是否选择的是最小化按钮
            if (WindowState == FormWindowState.Minimized)
            {
                //隐藏任务栏区图标
                this.ShowInTaskbar = false;
                //图标显示在托盘区
                notifyIcon.Visible = true;
                this.WindowState = FormWindowState.Minimized;
            }
            else
            {
                this.WindowState = FormWindowState.Minimized;
            }
            e.Cancel = true;
        }

        private void FormMain_SizeChanged(object sender, EventArgs e)
        {
            //判断是否选择的是最小化按钮
            if (WindowState == FormWindowState.Minimized)
            {
                //隐藏任务栏区图标
                this.ShowInTaskbar = false;
                //图标显示在托盘区
                notifyIcon.Visible = true;
                notifyIcon.ShowBalloonTip(3, "系统信息", "【数据传输】已启动", ToolTipIcon.Info);
            }
            else
            {
                this.ShowInTaskbar = true;//任务栏
            }
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.ShowInTaskbar = true;  //显示在系统任务栏
                this.WindowState = FormWindowState.Normal;  //还原窗体
            }
            this.WindowState = FormWindowState.Normal;
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //点击"是(YES)"退出程序
            if (MessageBox.Show("确定要退出程序?", "安全提示",
                        System.Windows.Forms.MessageBoxButtons.YesNo,
                        System.Windows.Forms.MessageBoxIcon.Warning)
                == System.Windows.Forms.DialogResult.Yes)
            {
                this.Close();                  //关闭窗体
                this.Dispose();                //释放资源
                Application.Exit();            //关闭应用程序窗体
            }
        }

        private void 查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GetQuery(false);
        }

        private void 查询未对码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GetQuery(true);
        }

        private void dGVDrug_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            GetSel(dGVDrug, e);
        }

        private void GetSel(DataGridView dgv, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                string itemid = dGVSale.CurrentRow.Cells["itemid"].Value.ToString().Trim();
                string drugcode = dgv.Rows[e.RowIndex].Cells["drugcode"].Value.ToString().Trim();

                string itemname = dGVSale.CurrentRow.Cells["itemname"].Value.ToString().Trim();
                string itemapproval = dGVSale.CurrentRow.Cells["itemapproval"].Value.ToString().Trim();
                string itemfactory = dGVSale.CurrentRow.Cells["itemfactory"].Value.ToString().Trim();
                string itempack = dGVSale.CurrentRow.Cells["itempack"].Value.ToString().Trim();
                string sql = "update [jryy_sp] set code='"+drugcode+"' where spid='"+itemid+"'";
                if (mssql.ExecuteSql(sql) > 0)
                {
                    blinfo.ForeColor = System.Drawing.Color.Green;
                    txtlinkinfo.ForeColor = blinfo.ForeColor;
                    blinfo.Text = "提示信息：【" + drugcode+"/" + itemname + "/" + itempack + "/" + itemfactory + "/" + itemapproval + "】关联成功！";
                    txtlinkinfo.Text = blinfo.Text;
                    dGVSale.CurrentRow.Cells["itemcode"].Value = drugcode;
                }
                else
                {
                    blinfo.ForeColor = System.Drawing.Color.Red;
                    txtlinkinfo.ForeColor = blinfo.ForeColor;
                    blinfo.Text = "提示信息：【" + drugcode + "/" + itemname + "/" + itempack + "/" + itemfactory + "/" + itemapproval + "】关联失败！";
                    txtlinkinfo.Text = blinfo.Text;
                }
            }
        }        

        private void dGVSale_SelectionChanged(object sender, EventArgs e)
        {
            blinfo.ForeColor = System.Drawing.Color.Black;
            txtlinkinfo.ForeColor = blinfo.ForeColor;
            blinfo.Text = "";
            txtlinkinfo.Text = "";
            string itemname = dGVSale.CurrentRow.Cells["itemname"].Value.ToString().Trim();
            string itemapproval = dGVSale.CurrentRow.Cells["itemapproval"].Value.ToString().Trim();
            string itemfactory = dGVSale.CurrentRow.Cells["itemfactory"].Value.ToString().Trim();
            string itempack = dGVSale.CurrentRow.Cells["itempack"].Value.ToString().Trim();

            string RowFilter = "approval='" + itemapproval + "'";
            dtdrug.DefaultView.RowFilter = RowFilter;
            dGVDrug.DataSource = dtdrug.DefaultView;
            init.AutoSizeColumn(dGVDrug);
        }

        private void 查询ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            string keyword = tSTBDrugSearch.Text;
            string RowFilter = "drugname like '%" + keyword + "%' or pack like '%" + keyword + "%' or pym like '%" + keyword + "%' or factory like '%" + keyword + "%' or approval like '%" + keyword + "%'";
            dtdrug.DefaultView.RowFilter = RowFilter;
            dGVDrug.DataSource = dtdrug.DefaultView;
            init.AutoSizeColumn(dGVDrug);
        }

        private void tSTBSearch_TextChanged(object sender, EventArgs e)
        {
            string keyword = tSTBDrugSearch.Text;
            if (keyword.Length >= 3)
            {
                string RowFilter = "drugname like '%" + keyword + "%' or pack like '%" + keyword + "%' or pym like '%" + keyword + "%' or factory like '%" + keyword + "%' or approval like '%" + keyword + "%'";
                dtdrug.DefaultView.RowFilter = RowFilter;
                dGVDrug.DataSource = dtdrug.DefaultView;
                init.AutoSizeColumn(dGVDrug);
            }
        }


        private void GetQuery(bool flag)
        {            
            string keyword = tSTBSaleSearch.Text;
            string sql = "";
            sql = "select a.djbh as itemorderid,a.rq as salesdate,"
             + "c.spid as itemid,c.spmch as itemname,c.shpgg as itempack,c.dw as itemunit,c.shengccj as itemfactory,wtscdw as lmanufacturer,c.sptm as itembarcode,c.pizhwh as itemapproval,c.code as itemcode, "
             + "b.pihao as batchno,b.sxrq as validity,b.baozhiqi as proddate,b.shl as salesqty,b.hshj as price,b.hsje as amount,count(1) over() as TotalNum "
             + " from [jryy_djhz] a(nolock),[jryy_djmx] b(nolock),[jryy_sp] c(nolock) "
             + " where a.djbh=b.djbh and b.spid=c.spid";
            if (flag)
            {
                sql += " and isnull(c.code,'')=''";
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                sql += " and a.djbh like '%"+keyword+"'";
            }
            sql+= " order by a.djbh,a.rq,b.spid";
            DataTable dt = mssql.ExecuteDt(sql);
            if (dt.Rows.Count > 0)
            {
                totalCount = (int)dt.Rows[0]["TotalNum"];
                dGVSale.DataSource = dt;               
                for (int i = 0; i < this.dGVSale.Columns.Count; i++)
                {
                    this.dGVSale.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                    this.dGVSale.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                }

                for (int i = 0; i < dtdrug.Rows.Count; i++)
                {
                    dtdrug.Rows[i]["pym"] = Pinyin.GetInitials(dtdrug.Rows[i]["drugname"].ToString().Trim());
                }
                dGVSale.Columns["TotalNum"].Visible = false;
                init.AutoSizeColumn(dGVSale);
                查询ToolStripMenuItem1.Enabled = true;
                label1.Text="记录数："+totalCount.ToString()+"条";
            }
        }



    }
}



